﻿@using Huirui.Cavan.Domain.MainBoundedContext.SalesModule
@model Huirui.Cavan.Presentation.ViewModel.SalesModule.ISalesViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.SALES))
{
    <div class="tool_bar">
        <input id="saleout_save" type="submit" style="display: none;" />
        <input id="saleout_reset" type="reset" style="display: none" />
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'"
            onclick="javascript:$('#saleout_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-copy',disabled:true">
            复制</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete'">
            删除</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-undo'"
            onclick="javascript:$('#saleout_reset').click()">重置</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-building'" onclick="openWindow('selectStockWindowFromSalesOrder')">
            按订单出库</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'">
            查询</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print'">
            打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'"
            onclick="toggleHeard()">折叠/展开</a>
    </div>
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>
                    订单日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.SalesDate, new { id = "saleDate", style = "height:18px", @class = "Wdate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    交货日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.DeadDate, new { id = "deliveryDate", style = "height:18px", @class = "Wdate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    客户订单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CustomerOrderCode, new { id = "customerOrderCode" })
            </td>
            <td class="c100">
                <label>
                    出库单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "id" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    客户*:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Customer.Id, new { id = "customerCodeForSales" })
            </td>
            <td colspan="2">
                @Html.TextBoxFor(m => m.Item.Customer.Name, new { id = "customerNameForSales" })
            </td>
            <td class="c100">
                <label>
                    销售人员:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.SaleEmployee.Id, new { id = "saleEmployeeCodeForSales" })
                @Html.HiddenFor(m => m.Item.SaleEmployee.Name, new { id = "saleEmployeeNameForSales" })
            </td>
            <td class="c100">
                <label>
                    接单仓库:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.WareHouse.Id, new { id = "wareHouseAddressForSales" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    币别:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Currency, new { id = "currency" })
            </td>
            <td class="c100">
                <label>
                    汇率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CurrencyRate, new { id = "currencyRate" })
            </td>
            <td class="c100">
                <label>
                    税率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.TaxRate, new { id = "taxRate" })
            </td>
            <td class="c100">
                <label>
                    开票类型:</label>
            </td>
            <td class="c160">
                @Html.DropDownListFor(m => m.Item.CheckType, typeof(SalesIdentifier.CheckType), new { id = "checkType" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    送货地址:</label>
            </td>
            <td colspan="4">
                @Html.TextBoxFor(m => m.Item.DeliveryAddress, new { id = "deliveryAddress" })
            </td>
            <td class="c160">
                <a>请选择常用送货地址</a>
            </td>
            <td class="c100">
                <a>送货单号:</a>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.DeliveryCode, new { id = "deliveryCode" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    备注:</label>
            </td>
            <td colspan="4">
                @Html.TextBoxFor(m => m.Item.Remark, new { id = "remark" })
            </td>
            <td class="c160">
                <a>请选择常用备注</a>
            </td>
            <td class="c100">
                <a>发票号码:</a>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CheckCode, new { id = "checkCode" })
            </td>
        </tr>
    </table>
    @Html.HiddenFor(m => m.StockInOutDetails, new { id = "stockInOutDetailsForSales" })
    @Html.HiddenFor(m => m.SalesOrders, new { id = "salesOrders" })
}
<table id="selectedStocksForSales" title="存货列表" toolbar="#sale_tb">
</table>
<div id="sale_tb">
    <a href="#" id="selectStockForSales" class="easyui-linkbutton" iconcls="icon-checked"
        plain="true" onclick="InitSelectStock('stocksForSales');openWindow('selectStockWindowForSales')">选择商品</a>
</div>
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.STOCK, new { purpose = "ForSales" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.CUSTOMER, new { purpose = "ForSales" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.WAREHOUSE, new { purpose = "ForSales" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.EMPLOYEE, new { purpose = "ForSales" }); }
@{ Html.RenderAction(ActionConst.STOCKSFROMSALESORDER, ControllerConst.STOCK); }

<script type="text/javascript">
    $(function ()
    {
        var lastIndex;
        var salesDetails;
        $('#selectedStocksForSales').datagrid({
            columns: [[
                { field: 'NoPrefixId', title: '存货编码', width: 100 },
                { field: 'Id', title: '存货编码', width: 100, hidden: true },
                { field: 'Name', title: '存货名称', width: 80 },
                { field: 'Specification', title: '规格', width: 60 },
                { field: 'UnitTransfer', title: '计量单位', width: 100 },
                { field: 'Number', title: '数量', width: 100, editor: { type: 'text'} },
                { field: 'AssistantNumber', title: '辅助数量', width: 100 },
                { field: 'StandardSalesPrice', title: '单价', width: 100 },
                { field: 'DiscountRate', title: '折扣率', width: 100 },
                { field: 'DiscountAmount', title: '折扣额', width: 80 },
                { field: 'SalesAmount', title: '销售额', width: 80 },
                { field: 'LocalCurrencySalesAmount', title: '本币销售额', width: 80 },
                { field: 'TaxRate', title: '税率', width: 80, editor: { type: 'text'} },
                { field: 'TaxAmount', title: '税额', width: 80 },
                { field: 'UnTaxAmount', title: '未税销售额', width: 80 },
                { field: 'SalesCost', title: '销售成本', width: 80 },
                { field: 'SalesOrderCode', title: '销售订单号', width: 80 },
                { field: 'Remark', title: '备注', width: 80 }
            ]]
        });

        $("#searchStockForSales").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksForSales').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        var currentIndex;
        var currentRow;
        var rowId;
        var number;
        var taxRate;

        $("#doSelectStockForSales").bind("click", function ()
        {
            $('#selectedStocksForSales').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksForSales').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++)
            {
                insert(rows[i].NoPrefixId, rows[i].Id, rows[i].Name, rows[i].Specification, rows[i].UnitTransfer, 0, 0, rows[i].StandardSalesPrice, rows[i].DiscountRate, 0, 0, 0, 0, 0, 0, 0, $("#salesOrderCode").val(), 'test');
            }
            closeWindow('selectStockWindowForSales')
        });

        $("#doSelectStocksFromSalesOrder").bind("click", function ()
        {
            $('#selectedStocksForSales').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksFromSalesOrder').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++)
            {
                $('#stocksFromSalesOrder').datagrid('endEdit', i);
                insert(rows[i].NoPrefixId, rows[i].Code, rows[i].Name, rows[i].Specification, rows[i].UnitTransfer, rows[i].CurrentStockOutNumber, 0, rows[i].CurrentStockOutPrice, rows[i].DiscountRate, 0, 0, 0, 0, 0, 0, 0, $("#salesOrderCode").val(), 'test');
            }
            closeWindow('selectStockWindowFromSalesOrder')
        });

        function insert(noPrefixId, id, name, specification, unitTransfer, number, assistantNumber, standardSalesPrice, discountRate, discountAmount, salesAmount, localCurrencySalesAmount, taxRate, taxAmount, unTaxAmount, salesCost, salesOrderCode, remark)
        {
            var rows = $('#selectedStocksForSales').datagrid('getRows');
            index = -1;
            if (rows.length == 0)
            {
                index = 0;
            }
            else
            {
                index = rows.length;
            }

            $('#selectedStocksForSales').datagrid('insertRow', {
                index: index,
                row: {
                    NoPrefixId: noPrefixId,
                    Id: id,
                    Name: name,
                    Specification: specification,
                    UnitTransfer: unitTransfer,
                    Number: number,
                    AssistantNumber: assistantNumber,
                    StandardSalesPrice: standardSalesPrice,
                    DiscountRate: discountRate,
                    DiscountAmount: discountAmount,
                    SalesAmount: salesAmount,
                    LocalCurrencySalesAmount: localCurrencySalesAmount,
                    TaxRate: taxRate,
                    TaxAmount: taxAmount,
                    UnTaxAmount: unTaxAmount,
                    SalesCost: salesCost,
                    SalesOrderCode: salesOrderCode,
                    Remark: remark
                }
            });
            $('#selectedStocksForSales').datagrid('selectRow', index);
            $('#selectedStocksForSales').datagrid('beginEdit', index);

            var ed = $('#selectedStocksForSales').datagrid('getEditors', index);
            for (var i = 0; i < ed.length; i++)
            {
                var e = ed[i];
                if (e.field == "Number")
                {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function ()
                    {
                        $('#selectedStocksForSales').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function ()
                    {
                        number = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForSales').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function ()
                        {
                            if ($(this).attr("field") == "TaxRate")
                            {
                                taxRate = $(this).find("input").val();
                            }
                        });
                        $("#" + rowId).find("td").each(function ()
                        {
                            if ($(this).attr("field") == "SalesAmount")
                            {
                                $(this).find("div").html(number * currentRow.StandardSalesPrice * (1 - parseFloat(currentRow.DiscountRate / 100)));
                            }
                            if ($(this).attr("field") == "DiscountAmount")
                            {
                                $(this).find("div").html(number * currentRow.StandardSalesPrice * (currentRow.DiscountRate / 100));
                            }
                            if ($(this).attr("field") == "TaxAmount")
                            {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardSalesPrice) * (1 - (100 / (parseFloat(taxRate) + 100)))).toFixed(2));
                            }
                            if ($(this).attr("field") == "UnTaxAmount")
                            {
                                $(this).find("div").html((number * currentRow.StandardSalesPrice * (1 - parseFloat(currentRow.DiscountRate / 100))) - parseFloat((number * currentRow.StandardSalesPrice) * (1 - (100 / (parseFloat(taxRate) + 100)))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForSales').datagrid('unselectRow', currentIndex);
                        currentRow.Number = number;

                        $.ajax({
                            url: '/stock/cbso?id=' + currentRow.Id + '&number=' + number,
                            type: 'Post',
                            success: function (data)
                            {
                                if (data)
                                {
                                    $("#" + rowId).find("td").each(function ()
                                    {
                                        if ($(this).attr("field") == "SalesCost")
                                        {
                                            $(this).find("div").html(data.SalesCost);
                                        }
                                    });
                                }
                            },
                            error: function ()
                            {
                                alert('系统繁忙，请稍候再试');
                            }
                        })
                    })
                }
                else if (e.field == "TaxRate")
                {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function ()
                    {
                        $('#selectedStocksForSales').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function ()
                    {
                        taxRate = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForSales').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function ()
                        {
                            if ($(this).attr("field") == "Number")
                            {
                                number = $(this).find("input").val();
                            }
                            if ($(this).attr("field") == "TaxAmount")
                            {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardSalesPrice) * (1 - (100 / (parseFloat(taxRate) + 100)))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForSales').datagrid('unselectRow', currentIndex);
                        currentRow.TaxRate = taxRate;
                    })
                }
            }
        }

        $("form[action^='/sales/add']").submit(function ()
        {
            var rows = $('#selectedStocksForSales').datagrid('getRows');
            stockInOutDetailsForSales = "[";
            for (var i = 0; i < rows.length; i++)
            {
                if (i == (rows.length - 1))
                {
                    stockInOutDetailsForSales = stockInOutDetailsForSales + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" :" + rows[i].StandardSalesPrice + ", \"TaxRate\" :" + rows[i].TaxRate + ", \"Description\" : \"" + rows[i].SalesOrderCode + "\" }";
                }
                else
                {
                    stockInOutDetailsForSales = stockInOutDetailsForSales + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" :" + rows[i].StandardSalesPrice + ", \"TaxRate\" :" + rows[i].TaxRate + ", \"Description\" : \"" + rows[i].SalesOrderCode + "\" },";
                }
            }
            stockInOutDetailsForSales = stockInOutDetailsForSales + "]";
            $("#stockInOutDetailsForSales").val(stockInOutDetailsForSales);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data)
                {
                    if (data.IsSuccess)
                    {
                        alert(data.Messages[0]);
                    }
                },
                error: function ()
                {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#searchStockFromSalesOrder").submit(function ()
        {
            var stockOutStatues = '';
            $("input[type='checkbox'][name='stockOutStatus']:checked").each(function ()
            {
                stockOutStatues = stockOutStatues + $(this).val() + ",";
            });
            $("#stockOutStatues").val(stockOutStatues);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result)
                {
                    if (result.total > 0)
                    {
                        $('#stocksFromSalesOrder').datagrid({
                            columns: [[
                                { field: 'IsSelected', title: '选择', width: 60, checkbox: true },
                                { field: 'CustomerName', title: '客户', width: 80, align: 'right' },
                                { field: 'SalseOrderCode', title: '销售订单编号', width: 60 },
                                { field: 'Name', title: '存货', width: 80, align: 'right' },
                                { field: 'StockOutStatus', title: '出库状态', width: 80, align: 'right' },
                                { field: 'DeliveryDate', title: '交货日期', width: 60 },
                                { field: 'Number', title: '订单数量', width: 100 },
                                { field: 'UnStockOutNumber', title: '未出库数量', width: 80, align: 'center' },
                                { field: 'CurrentStockOutNumber', title: '数量', width: 80, align: 'center', editor: 'numberbox' },
                                { field: 'CurrentStockOutPrice', title: '价格', width: 100, editor: 'numberbox' },
                                { field: 'Address', title: '存货地点', width: 100 }
                            ]],
                            data: result
                        });
                        $("#salesOrders").val(result.SalesOrders);
                        var salesOrders = JSON.parse(result.SalesOrders);
                        $("#employee").val(salesOrders[0].SaleEmployeeCode);
                        $("#customer").val(salesOrders[0].CustomerCode);
                        $("#currency").val(salesOrders[0].Currency);
                        $("#currencyRate").val(salesOrders[0].CurrencyRate);
                        $("#wareHouse").val(salesOrders[0].WareHouseCode);
                        $("#deliveryAddress").val(salesOrders[0].DeliveryAddress);
                        $("#taxRate").val(salesOrders[0].TaxRate);
                        $("#remark").val(salesOrders[0].Remark);

                        var rows = $('#stocksFromSalesOrder').datagrid('getRows');
                        for (var i = 0; i < rows.length; i++)
                        {
                            $('#stocksFromSalesOrder').datagrid('beginEdit', i);
                        }
                    }
                    else
                    {
                        $('#stocksFromSalesOrder').datagrid('loadData', { total: 0, rows: [] });
                    }
                },
                error: function ()
                {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#customerCodeForSales").bind("click", function () {
            InitSelectCustomer('customersForSales');
            openWindow("selectCustomerWindowForSales");
        });

        $("#searchCustomerForSales").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#customersForSales').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectCustomerForSales").bind("click", function () {
            var currentRow = $('#customersForSales').datagrid('getSelected');
            $("#customerCodeForSales").val(currentRow.Id);
            $("#customerNameForSales").val(currentRow.Name);
            closeWindow("selectCustomerWindowForSales");
        });

        $("#wareHouseAddressForSales").bind("click", function () {
            InitSelectWareHouse('wareHousesForSales');
            openWindow("selectWareHouseWindowForSales");
        });

        $("#searchWareHouseForSales").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#wareHousesForSales').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectWareHouseForSales").bind("click", function () {
            var currentRow = $('#wareHousesForSales').datagrid('getSelected');
            $("#wareHouseCodeForSales").val(currentRow.Id);
            $("#wareHouseAddressForSales").val(currentRow.Address);
            closeWindow("selectWareHouseWindowForSales");
        });

        $("#saleEmployeeCodeForSales").bind("click", function () {
            InitSelectEmployee('employeesForSales');
            openWindow("selectEmployeeWindowForSales");
        });

        $("#searchEmployeeForSales").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#employeesForSales').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectEmployeeForSales").bind("click", function () {
            var currentRow = $('#employeesForSales').datagrid('getSelected');
            $("#saleEmployeeCodeForSales").val(currentRow.Id);
            $("#saleEmployeeNameForSales").val(currentRow.Name);
            closeWindow("selectEmployeeWindowForSales");
        });

    });
</script>
